package com.example.prison.util;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * 消息处理类
 *
 * @author PP LU
 */
public class TCPServerHandler extends SimpleChannelInboundHandler<String> {

    private final Logger logger = LoggerFactory.getLogger(TCPServerHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = insocket.getAddress().getHostAddress();
        int port = insocket.getPort();
        logger.info("收到客户端[ip:" + clientIp + "：" + port + "]连接");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        logger.error("发生异常:" + cause.getMessage());
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
//        String id = CommonUtil.getId(msg);
//        String devId = CommonUtil.getDevID(msg);
//        // 相应客户端
//        if (id.equals("1")) {
            ctx.channel().writeAndFlush(msg);
//            // 修改数据库中对应设备的状态
//
//        } else if (id.equals("box_2")) {
//            ctx.channel().writeAndFlush("ok");
//        }
//        // 保存channel,key
//        // deviceId为空时表示设备断线重连
//        if (!NettyChannelManager.hasKey(devId)) {
//            NettyChannelManager.add(devId, ctx.channel());
//        }
//        // 操作数据
//        this.operMessage(msg);
        System.out.println(msg);
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ctx.close();
    }

}
